package com.zyj.core.config;

import com.zyj.core.executor.CachingExecutor;
import com.zyj.core.executor.Executor;
import com.zyj.core.executor.SimpleExecutor;
import com.zyj.core.handler.parameterhandler.DefaultParameterHandler;
import com.zyj.core.handler.parameterhandler.ParameterHandler;
import com.zyj.core.handler.resultsethandler.DefaultResuiltSetHandler;
import com.zyj.core.handler.resultsethandler.ResultSetHandler;
import com.zyj.core.handler.statementhandler.RoutingStatementHandler;
import com.zyj.core.handler.statementhandler.StatementHandler;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于存储全局配置文件和映射文件中的数据
 */
public class Configuration {

    private DataSource dataSource;

    private Map<String, MappedStatement> mappedStatements = new HashMap<>();

    // 二级缓存默认开启
    private boolean cacheEnabled = true;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public MappedStatement getMappedStatementById(String statementId) {
        return mappedStatements.get(statementId);
    }

    public void addMappedStatement(String statementId, MappedStatement mappedStatement) {
        this.mappedStatements.put(statementId, mappedStatement);
    }

    /**
     * 根据配置信息选择某种类型的执行器，后续用来执行sql，如果没有配置，则默认选择SimpleExecutor
     *
     * @param executorType
     * @return
     */
    public Executor newExecutor(String executorType) {
        // 如果没有指定executorType，则默认是simple
        executorType = executorType == null || executorType.equals("") ? "simple" : executorType;
        Executor executor = null;

        if ("simple".equals(executorType)) {
            executor = new SimpleExecutor();// 创建真正干活的执行器
        }

        /**
         * 如果开启了二级缓存，则在选择了真正的执行器之后，需要先进CachingExecutor查询二级缓存，若CachingExecutor中的二级缓存没有命中，再由CachingExecutor调用此处选择好的真正的执行器来执行查询
         */
        // 装饰模式，在SimpleExecutor的基础上做了装饰增强，装饰功能结束后，依然还是调用SimpleExecutor执行
        // 默认开启二级缓存
        if (cacheEnabled) {
            // 创建二级缓存处理功能的执行器，但是该执行器还是要继续往下执行，得调用真正干活的执行器
            executor = new CachingExecutor(executor);
        }

        return executor;
    }

    public StatementHandler newStatementHandler(String statementType) {
        // 由RoutingStatementHandler路由到真正的Statement处理器
        RoutingStatementHandler routingStatementHandler = new RoutingStatementHandler(statementType, this);
        return routingStatementHandler;
    }

    public ParameterHandler newParameterHandler() {
        return new DefaultParameterHandler();
    }

    public ResultSetHandler newResultSetHandler() {
        return new DefaultResuiltSetHandler();
    }
}
